package com.sy.controller;

import com.sy.model.Article;
import com.sy.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author songyi
 * @date 2020/6/21 0021 23:01
 * @description
 */
@Controller
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 配置多个URL
     * @param pageNo 请求页码
     * @param model
     * @return
     */
    @RequestMapping(value = {"/index", "/index/{pageNo}"})
    public String index(@PathVariable(value = "pageNo", required = false) Integer pageNo, Model model) {
        //每页数量
        int pageSize = 3;
        //总记录数
        int total = articleService.findCount();
        //总页数
        int totalPage = total % pageSize == 0 ? (total / pageSize) : (total / pageSize) + 1;

        //根据分页，设置查询条件
        int offset = 0;
        int limit = offset + pageSize;
        if (null == pageNo || pageNo <= 0) {
            offset = 0;
            limit = offset + pageSize;
            pageNo = 1;
        } else {
            offset = (pageNo - 1) * pageSize;
            limit = offset + pageSize;
        }

        List<Article> articles = articleService.selectList(offset, limit);
        // 查询结果
        model.addAttribute("articles", articles);
        // 前一页页码
        model.addAttribute("previous", pageNo - 1);
        // 后一页页码
        model.addAttribute("next", pageNo + 1);
        // 总页数
        model.addAttribute("totalPage", totalPage);
        return "/client/index";
    }
}
